<template>
  <div style="margin: 10px;padding: 10px">
    <div style="margin-bottom: 10px">
      <el-select v-model="printer" placeholder="请选择">
        <el-option
            v-for="(item, index) in printerLists"
            :key="index"
            :label="item.displayName"
            :value="item.name">
        </el-option>
      </el-select>
      <el-button @click="toPrint">打印</el-button>
    </div>
    <div style="display: flex;margin-bottom: 8px">
      <el-select v-model="statusVal" placeholder="请选择" style="margin-right: 5px" @change="getLists">
        <el-option
            v-for="(item, index) in opts"
            :key="index"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker
          v-model="date02"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="getLists">
      </el-date-picker>
    </div>

    <el-table :data="lists" border style="width: 100%" height="800px">
      <el-table-column prop="_id" label="标识">
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          {{ scope.row | getStatus }}
        </template>
      </el-table-column>
      <el-table-column prop="printer" label="打印机">
        <template slot-scope="scope">
          {{ scope.row | getPrinter }}
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.create_time | formatDate }}
        </template>
      </el-table-column>
      <el-table-column prop="start_time" label="开始时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.start_time | formatDate }}
        </template>
      </el-table-column>
      <el-table-column prop="print_time" label="打印时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.print_time | formatDate }}
        </template>
      </el-table-column>
      <el-table-column prop="print_msg" label="原因" fixed="right">
        <template slot-scope="scope">
          {{ scope.row | getMsg }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200px">
        <template slot-scope="scope">
          <el-button type="warning" @click="del(scope.row)">删除</el-button>
          <el-button @click="openPage(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    <msg-form :dia-visible="v" :info="info" @close="closePage"/>-->
  </div>
</template>

<script>
import {getPrinters, parseTime} from "@/utils";
import {ipcRenderer} from "electron";
// import MsgForm from "@/components/MsgForm";

export default {
  name: "Print",
  // components: {MsgForm},
  filters: {
    getPrinter(val) {
      if (!val || !val.msg) {
        return '未知打印机'
      }
      try {
        const msg = JSON.parse(val.msg)
        return msg.printer ? msg.printer : '未知打印机'
      } catch (e) {
        return '未知打印机'
      }
    },
    getMsg(val) {
      if (!val || !val.print_result) {
        return ''
      }

      try {
        const data = JSON.parse(val.print_result)
        return data.msg ? data.msg : '未知'
      } catch (e) {
        return '未知原因'
      }
    },
    formatDate(val) {
      if (!val) {
        return ''
      }
      return parseTime(val, '{y}-{m}-{d} {h}:{i}:{s}')
    },
    getStatus(val) {
      const status = {0: "未开始", 1: "打印成功", 2: "打印失败"}
      let statusText = status[val.status] ? status[val.status] : '未知'
      if (!val.status && val.start_time) {
        statusText = '已开始'
      }
      return statusText
    }
  },
  data: function () {
    return {
      printer: undefined,
      date02: [],
      statusVal: undefined,
      printerLists: [],
      printTime: 0,
      printCount: 0,
      successNum: 0,
      failedNum: 0,
      lists: [],
      v: false,
      info: {},
      query: {},
      opts: [
        { label: '全部', value: undefined },
        { label: '未开始', value: 0 },
        { label: '打印成功', value: 1 },
        { label: '打印失败', value: 2 },
      ]
    }
  },
  mounted() {
    this.$bus.on('getPrinters', this.getPrinters)
    this.$bus.on('updateDocs', this.getLists)

    this.getPrintList()
    this.addPrints()
    this.registerPrintResult()
    this.getLists()
    setInterval(
      () => {
        this.getLists()
      }, 60000
    )
  },
  beforeDestroy() {
    this.$bus.off('getPrinters', this.getPrinters)
    this.$bus.off('updateDocs', this.getLists)
  },
  methods: {
    addPrints() {
      // 获取打印结果
      const {ipcRenderer} = require('electron')
      const that = this
      ipcRenderer.on('addPrint', (event, args) => {

        if (args.length) {

          for (let i = 0; i < args.length; i++) {
            that.$db.insert(args[i], function (err, doc) {
              console.log('保存err', err)
              console.log('doc: ', doc)
            })
          }

        }
        console.log('加载列表')
        that.getLists()
      })
    },
    del(val) {
      const that = this
      this.$db.remove({ _id: val._id }, {}, function (err, num) {
        console.log('删除结果: ', err, ', num: ', num)
        if (!err) {
          that.$message.success('删除成功')
        }
        that.getLists()
      })
    },
    openPage(val) {
      this.v = true
      this.info = val
    },
    closePage() {
      this.v = false
      this.info = {}
    },
    getLists() {
      this.query = {}

      if (this.statusVal !== undefined) {
        this.query.status = this.statusVal
      }

      if (this.date02 && this.date02.length) {
        const date02 = JSON.parse(JSON.stringify(this.date02))
        this.query.create_time = {
          $gte: Math.round((new Date(date02[0])).getTime() / 1000),
          $lte: Math.round((new Date(date02[1])).getTime() / 1000),
        }
      }
      const model = this.$db.find(this.query)
      const that = this
      model.sort({create_time: -1})
        .exec(
          function (err, docs) {
            that.lists = []
            // eslint-disable-next-line no-empty
            if (!err && docs) {
              that.lists = docs
            }
          }
        )
    },
    addDb() {
    },
    registerPrintResult() {
      // 获取打印结果
      const {ipcRenderer} = require('electron')
      const that = this
      ipcRenderer.on('printRet', (event, args) => {
        console.log('打印结果: ', args)
        that.printTime = 0
        if (args.code) {
          if (args.code === 200) {
            that.successNum++
          } else {
            that.failedNum++
          }
        }
        that.getLists()
      })
    },
    getPrinters(val) {
      this.printerLists = val
      for (let i = 0; i < this.printerLists.length; i++) {
        if (this.printerLists[i].isDefault) {
          this.printer = this.printerLists[i].name
        }
        if (this.printerLists[i].status !== 0) {
          this.printerLists[i].displayName += '(不可用)'
        }
      }
    },
    toPrint() {

      if (!this.printer) {
        this.$message.warning('请选择打印机')
        return
      }

      this.$message.success('静默打印')
      // 打印图片
      const id = 100 * Math.round(Math.random() * 100)
      const info = {
        status: 0,
        id: id,
        msg: JSON.stringify({
          id: id,
          isSilent: true, // 是否静默打印
          type: 'img',
          url: 'https://hx168.oss-cn-shenzhen.aliyuncs.com/hxy_new/sf/20220702/sf_SF1358428603828.png',
          printer: this.printer
        }),
        create_time: Math.round((new Date() / 1000)),
        start_time: 0,
        print_time: 0,
        user_id: 1,
        print_result: ''
      }

      const that = this
      that.$db.findOne({id: id}, function (err, doc) {
        if (!doc) {
          that.$db.insert(info, function (err, newDoc) {
            if (!err) {
              console.log('保存成功: ', newDoc)
            }
          })
        }
      })


      // const { ipcRenderer } = require('electron')

      // ipcRenderer.send('toPrint', {
      //   id: 0 + 1,
      //   isSilent: true, // 是否静默打印
      //   type: 'img',
      //   url: 'https://hx168.oss-cn-shenzhen.aliyuncs.com/hxy_new/sf/20220702/sf_SF1358428603828.png',
      //   printer: this.printer
      // })
      // for (let i = 0; i < 3; i++) {
      //
      //   // if (this.printTime) {
      //   //   while (this.printTime) {
      //   //     const te = Math.round(new Date() / 1000) - this.printTime
      //   //     if (te % 3 === 0) {
      //   //       console.log('正在等待打印', te)
      //   //     }
      //   //     if (te > 300) {
      //   //       console.log('严重超时5分钟!')
      //   //       this.printTime = 0
      //   //       break
      //   //     }
      //   //   }
      //   // }
      //   const { ipcRenderer } = require('electron')
      //   ipcRenderer.send('toPrint', {
      //     id: i + 1,
      //     isSilent: true, // 是否静默打印
      //     type: 'img',
      //     url: 'https://hx168.oss-cn-shenzhen.aliyuncs.com/hxy_new/sf/20220702/sf_SF1358428603828.png',
      //     printer: this.printer
      //   })
      //
      //   this.printTime = Math.round(new Date() / 1000)
      //   this.printCount++
      // }
    },
    getPrintList() {
      this.$message.success('获取打印机列表')
      getPrinters()
    },
  }
}
</script>

<style scoped>
</style>
